package com.mpgame.handler;

import com.mpgame.common.handler.BaseHandler;
import com.mpgame.common.proto.*;
import com.mpgame.common.utils.Log;
import com.mpgame.connection.ChannelRegistry;
import com.mpgame.database.redis.model.UserTokenInfo;
import com.mpgame.database.redis.utils.PlayerOnlineUtil;
import com.mpgame.database.redis.utils.TokenUtil;

import io.netty.channel.ChannelHandlerContext;

public class AuthHandler extends BaseHandler {

    public AuthHandler() {
        super("AuthHandler", 1, true);
    }

    @Override
    public boolean handle(ChannelHandlerContext ctx, GamePacket pkt) {
        try {
            switch (pkt.getCmd()) {
                case GAME_AUTH_REQ:
                    return verifyToken(ctx, pkt);
                default:
                    Log.warn("未知的命令类型，无法验证：" + pkt.getCmd());
                    return false;
            }
        } catch (Exception e) {
            Log.err("转发处理器处理异常：" + e.getMessage());
            return false;
        }
    }

    private boolean verifyToken(ChannelHandlerContext ctx, GamePacket pkt) {
        try {
            GameAuthReq req = GameAuthReq.parseFrom(pkt.getData());

            String token = req.getToken();

            Log.info("收到认证请求：" + token);

            UserTokenInfo userTokenInfo = TokenUtil.getUserTokenInfoFromToken(token);
            if (userTokenInfo != null) {
                String nickname = userTokenInfo.getNickname();
                String accountId = String.valueOf(userTokenInfo.getAccountId());
                // 认证成功
                UserTokenInfoRsp arsp = UserTokenInfoRsp.newBuilder()
                    .setAccountId(userTokenInfo.getAccountId())
                    .setUsername(userTokenInfo.getUsername())
                    .setNickname(userTokenInfo.getNickname())
                    .setPosX(userTokenInfo.getPosX())
                    .setPosY(userTokenInfo.getPosY())
                    .setSceneId(userTokenInfo.getSceneId())
                    .build();

                GamePacket grsp = GamePacket.newBuilder()
                        .setCmd(CmdId.GAME_AUTH_RSP)
                        .setEc(ErrorCode.SUCCESS)
                        .setData(arsp.toByteString())
                        .build();
                GamePacket brsp = GamePacket.newBuilder()
                    .setCmd(CmdId.GAME_PLAYER_JOIN)
                    .setEc(ErrorCode.SUCCESS)
                    .setData(arsp.toByteString())
                    .build();
                ChannelRegistry.addPlayerConnection(accountId, ctx.channel());
                PlayerOnlineUtil.addPlayerToOnlineList(accountId);
                // 将自己的信息单独返回给客户端
                ctx.writeAndFlush(grsp);
                // 将自己加入游戏的信息广播给所有客户端（排除自己）
                ChannelRegistry.broadcast(brsp, ctx.channel());

                Log.info("玩家 " + accountId + "（" + nickname + "）认证成功。连接已建立！");
                return true;
            } else {
                // 认证失败
                GamePacket grsp = GamePacket.newBuilder()
                        .setCmd(CmdId.GAME_AUTH_RSP)
                        .setEc(ErrorCode.AUTH_FAILED)
                        .setData(ErrMsg.newBuilder().setErrMsg("Token验证失败").build().toByteString())
                        .build();
                

                ctx.writeAndFlush(grsp);

                ChannelRegistry.kick(ctx.channel(), "Token验证失败");

                return false;
            }
        } catch (Exception e) {
            Log.err("Token验证失败：" + e.getMessage());
            return false;
        }
    }
}
